import socket  # udp网络功能
from utime import sleep  # 延时功能
import network  # 入网功能
from machine import Pin

led = Pin(2, Pin.OUT)  # 创建灯对象

# 连接wifi


def do_connect():
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    if not wlan.isconnected():
        print('connecting to network...')
        wlan.connect('XZY_wifi', 'xiaozhiyi99.com')  # 填写wifi信息
        i = 1
        while not wlan.isconnected():
            print("正在链接...{}".format(i))
            i += 1
            led.value(led.value() ^ 1)  # 如果没有连上网络让板载led闪烁
            sleep(0.8)
    print('network config:', wlan.ifconfig())  # 打印入网ip信息

# 启动网络功能（UDP）


def start_udp():
    udp_socket = socket.socket(
        socket.AF_INET, socket.SOCK_DGRAM)  # 创建udp接收data数据
    udp_socket.bind(("0.0.0.0", 9527))  # 绑定端口号
    return udp_socket


def main():
    do_connect()  # 连接wifi
    udp_socket = start_udp()  # 创建UDP
    print("udp_socket", udp_socket)
    led.value(0)
    udp_socket.sendto('LED_OFF', ("192.168.99.158", 9528))
    while True:
        recv_data, sender_info = udp_socket.recvfrom(1024)  # 接收网络数据
        print("{}发送{}".format(sender_info, recv_data))  # 将接收的数据串口打印
        recv_data_str = recv_data.decode("utf-8")
        try:
            print(recv_data_str)
        except Exception as ret:
            print("error:", ret)

        # 处理接收的数据
        if recv_data_str == "LED_ON":
            print("打开板载led灯...")
            led.value(1)
            udp_socket.sendto('LED_ON', ("192.168.99.158", 9528))
        elif recv_data_str == "LED_OFF":
            print("关闭板载led灯...")
            led.value(0)
            udp_socket.sendto('LED_OFF', ("192.168.99.158", 9528))


if __name__ == "__main__":
    main()  # 运行主程序
